package tbalert.web.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;

import tbalert.hibernate3.Finder;
import tbalert.hibernate3.HibernateBaseDao;
import tbalert.page.Pagination;
import tbalert.web.dao.BaseInfoDao;
import tbalert.web.entity.BaseInfo;
import tbalert.web.entity.Blxxk;
import tbalert.web.entity.Fxpgb;
import tbalert.web.entity.Ymjg;

public class BaseInfoDaoImpl extends HibernateBaseDao<BaseInfo, String>
		implements BaseInfoDao {

	@Override
	public BaseInfo deleteById(String kicid) {
		BaseInfo entity = super.get(kicid);
		if (entity != null) {
			getSession().delete(entity);
		}
		return entity;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<BaseInfo> findByFinder(Finder finder) {
		List<Object[]> objectsList = (List<Object[]>) super.find(finder);

		List<BaseInfo> baseInfoList = new ArrayList<BaseInfo>();
		for (Object[] objects : objectsList) {
			if (objects.length == 2) {
				BaseInfo baseInfo = (BaseInfo) objects[0];
				Ymjg ymjg = (Ymjg) objects[1];
				baseInfo.setYmjg(ymjg);
				baseInfoList.add(baseInfo);
			} else {
				BaseInfo baseInfo = (BaseInfo) objects[0];
				Blxxk blxxk = (Blxxk) objects[1];
				Fxpgb fxpgb = (Fxpgb) objects[2];
				baseInfo.setBlxxk(blxxk);
				baseInfo.setFxpgb(fxpgb);
				baseInfoList.add(baseInfo);
			}
		}
		return baseInfoList;
	}

	@Override
	public Pagination findByFinder(Finder finder, int pageNo, int pageSize) {
		return super.find(finder, pageNo, pageSize);
	}

	@Override
	public BaseInfo findByKicid(String kicid) {
		return get(kicid);
	}

	@Override
	public String getMaxKicid(String dwid) {
		String sql = "select max(kicid) from tb_baseinfo where kicid like '"
				+ dwid + "%'";
		return (String) getSession().createSQLQuery(sql).uniqueResult();
	}

	@Override
	public BaseInfo save(BaseInfo bean) throws HibernateException {
		getSession().save(bean);
		return bean;
	}

	@Override
	public Integer unfinished(String dwid) {
		Integer res = (Integer) getSession().createSQLQuery(
				"select count(*) from tb_baseInfo where djdw='" + dwid
						+ "' and submit=0").uniqueResult();
		return res > 0 ? res : null;
	}

	@Override
	protected Class<BaseInfo> getEntityClass() {
		getSession();
		return BaseInfo.class;
	}
}
